package com.base.common.provider;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.faces.model.SelectItem;

import com.base.commons.SpringBeanHolder;
import com.base.organization.DAPType;
import com.base.organization.entity.CentralUnit;
import com.base.organization.entity.DepartmentalUnit;
import com.base.organization.service.IOrganizationService;
import com.base.security.entity.SecurityUser;
import com.base.security.service.SecurityEntityManager;

public class SecuritySelectItemProvider {

	public final static String PRI_PERSON = "person:";
	public final static String PRI_DEPT = "dep:";

	/**
	 * 取某个部门下面的所有员工
	 * 
	 * @param depId
	 *            部门id
	 * @param nameSelect
	 *            是否存姓名
	 * @return
	 */
	public static SelectItem[] getPersonsOfDept(Integer depId,
			boolean nameSelect) {
		if (depId == null || "".equals(depId))
			return null;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		List<SecurityUser> users = orgService.getPersonsOfDept(depId);
		if (users.isEmpty())
			return null;
		SelectItem[] result = new SelectItem[users.size()];
		for (int i = 0; i < users.size(); i++) {
			if (nameSelect) {
				result[i] = new SelectItem(users.get(i).getFullname(), users
						.get(i).getFullname());
			} else {
				result[i] = new SelectItem(users.get(i).getUserId(), users.get(
						i).getFullname());
			}
		}
		return result;
	}

	/**
	 * 得到所有用户的选择项
	 * 
	 * @param nameSelect
	 *            是否存姓名
	 * @return
	 */
	public static SelectItem[] getAllPerson(boolean nameSelect) {
		SecurityEntityManager seManager = SpringBeanHolder
				.getBean("securityEntityManager");
		List<SecurityUser> users = seManager.getAllUsers();
		if (users.isEmpty())
			return null;
		SelectItem[] result = new SelectItem[users.size()];
		for (int i = 0; i < users.size(); i++) {
			if (nameSelect) {
				result[i] = new SelectItem(users.get(i).getFullname(), users
						.get(i).getFullname());
			} else {
				result[i] = new SelectItem(users.get(i).getUserId(), users.get(
						i).getFullname());
			}
		}
		return result;
	}

	/**
	 * 得到所有部门的选择项，没有层级之分
	 * 
	 * @param nameSelect
	 * @return
	 */
	public static SelectItem[] getAllDepartment(boolean nameSelect) {
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		List<DepartmentalUnit> deptList = orgService.getAllDepartment();
		if (deptList.isEmpty())
			return null;
		SelectItem[] result = new SelectItem[deptList.size()];
		for (int i = 0; i < deptList.size(); i++) {
			if (nameSelect) {
				result[i] = new SelectItem(deptList.get(i).getName(), deptList
						.get(i).getName());
			} else {
				result[i] = new SelectItem(deptList.get(i)
						.getDepartmentalUnitId(), deptList.get(i).getName());
			}
		}
		return result;
	}

	/**
	 * 得到所有的机构，没有层级之分
	 * 
	 * @param nameSelect
	 * @return
	 */
	public static SelectItem[] getAllCentralUnit(boolean nameSelect) {
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		List<CentralUnit> all = orgService.getAllCentralUnit();
		if (all.isEmpty())
			return null;
		SelectItem[] result = new SelectItem[all.size()];
		for (int i = 0; i < all.size(); i++) {
			if (nameSelect) {
				result[i] = new SelectItem(all.get(i).getName(), all.get(i)
						.getName());
			} else {
				result[i] = new SelectItem(all.get(i).getCentralUnitId(), all
						.get(i).getName());
			}
		}
		return result;
	}

	/**
	 * 需要修改成为有层次的结构,add by wt 20110218 edited by exit 20110219 调整为有层次的体系
	 * 
	 * @author wangtao
	 * @param userId
	 * @return
	 */
	public static SelectItem[] getManagedDepts(Integer userId) {
		return getManagedDepts(userId, false);
	}

	public static SelectItem[] getManagedDepts(Integer userId,
			boolean isShowBelong) {

		List<SelectItem> result = new LinkedList<SelectItem>();

		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");

		if (isShowBelong) {
			List<DepartmentalUnit> belongs = orgService.getDeptsOfPerson(
					userId, (DAPType) null);
			for (DepartmentalUnit du : belongs) {
				result.add(new SelectItem(du.getDepartmentalUnitId(), "*"
						+ du.getName()));
			}
		}
		Set<Integer> rSet = new HashSet<Integer>();
		List<DepartmentalUnit> depts = orgService.getDirectManagedDeps(userId);
		if (depts.size() > 0) {
			for (DepartmentalUnit dept : depts) {
				addManagedDep(dept, result, rSet, "", 0);
			}
		}
		SelectItem[] ret = new SelectItem[result.size()];
		for (int i = 0; i < result.size(); i++) {
			SelectItem si = result.get(i);
			ret[i] = si;
		}
		return ret;
	}

	private static void addManagedDep(DepartmentalUnit du,
			List<SelectItem> result, Set<Integer> existedDU,
			String depLevelStr, int level) {
		if (existedDU.contains(du.getDepartmentalUnitId()))
			return;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		existedDU.add(du.getDepartmentalUnitId());
		// 先把部门加上
		result.add(new SelectItem(du.getDepartmentalUnitId(), depLevelStr
				+ du.getName()));
		String dLevelStr = null;
		if (level == 0)
			dLevelStr = "|—";
		else
			dLevelStr = depLevelStr + "——";
		// 先出子部门
		List<DepartmentalUnit> subList = orgService.getDirectChildDepts(du
				.getDepartmentalUnitId());
		if (subList != null)
			for (DepartmentalUnit subDu : subList) {
				addManagedDep(subDu, result, existedDU, dLevelStr, level + 1);
			}
		// 再处理间接部门
		List<SecurityUser> persons = orgService.getPersonsOfDept(du
				.getDepartmentalUnitId());
		// 再出部门下的人的主管部门
		for (SecurityUser user : persons) {
			List<DepartmentalUnit> directDU = orgService
					.getDirectManagedDeps(user.getUserId());
			for (DepartmentalUnit subdu : directDU) {
				addManagedDep(subdu, result, existedDU, dLevelStr, level + 1);
			}
		}
	}

	/**
	 * 取某人主管的所有员工
	 * 
	 * @param depId
	 *            部门id
	 * @param nameSelect
	 *            是否存姓名
	 * @return
	 */
	public static SelectItem[] getManagedPersons(Integer userId,
			boolean nameSelect) {
		if (userId == null || "".equals(userId))
			return null;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		SecurityEntityManager seManager = SpringBeanHolder
				.getBean("securityEntityManager");
		List<DepartmentalUnit> directDU = orgService
				.getDirectManagedDeps(userId);
		List<Object[]> resultList = new LinkedList<Object[]>();
		// 先把自己加上
		resultList.add(new Object[] { userId,
				seManager.getUserById(String.valueOf(userId)).getFullname() });
		// 再处理主管部门
		Set<Integer> rSet = new HashSet<Integer>();
		for (DepartmentalUnit du : directDU) {
			addManagedPersonOfDep(du, resultList, rSet, "", "——", 0);
		}
		SelectItem[] result = new SelectItem[resultList.size()];
		for (int i = 0; i < resultList.size(); i++) {
			Object[] r = resultList.get(i);
			if (nameSelect) {
				result[i] = new SelectItem((String) r[1], (String) r[1]);
			} else {
				result[i] = new SelectItem((Integer) r[0], (String) r[1]);
			}
		}
		return result;
	}

	private static void addManagedPersonOfDep(DepartmentalUnit du,
			List<Object[]> resultList, Set<Integer> existedDU,
			String depLevelStr, String personLevelStr, int level) {
		if (existedDU.contains(du.getDepartmentalUnitId()))
			return;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		existedDU.add(du.getDepartmentalUnitId());
		// 先把部门加上
		resultList.add(new Object[] { 0, depLevelStr + du.getName() });
		// 再处理部门下的人
		List<SecurityUser> persons = orgService.getPersonsOfDept(du
				.getDepartmentalUnitId());
		// 先出人
		for (SecurityUser user : persons) {
			resultList.add(new Object[] { user.getUserId(),
					personLevelStr + user.getFullname() });
		}
		// 再出部门下的人的主管部门
		for (SecurityUser user : persons) {
			List<DepartmentalUnit> directDU = orgService
					.getDirectManagedDeps(user.getUserId());
			for (DepartmentalUnit subdu : directDU) {
				String dLevelStr = "";
				if (level == 0)
					dLevelStr = "|—";
				else
					dLevelStr = depLevelStr + "——";
				String pLevelStr = personLevelStr + "——";
				addManagedPersonOfDep(subdu, resultList, existedDU, dLevelStr,
						pLevelStr, level + 1);
			}
		}
	}

	/**
	 * 取某人主管的所有部门和员工 两个均可选
	 * 
	 * @param depId
	 *            部门id
	 * @return
	 */
	public static SelectItem[] getManagedDepAndPerson(Integer userId) {
		if (userId == null || "".equals(userId))
			return null;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		SecurityEntityManager seManager = SpringBeanHolder
				.getBean("securityEntityManager");
		List<DepartmentalUnit> directDU = orgService
				.getDirectManagedDeps(userId);
		List<String[]> resultList = new LinkedList<String[]>();
		// 先把自己加上
		resultList.add(new String[] { PRI_PERSON + String.valueOf(userId),
				seManager.getUserById(String.valueOf(userId)).getFullname() });
		// 再处理主管部门
		Set<Integer> rSet = new HashSet<Integer>();
		for (DepartmentalUnit du : directDU) {
			addManagedDepAndPerson(du, resultList, rSet, "", "——", 0);
		}
		SelectItem[] result = new SelectItem[resultList.size()];
		for (int i = 0; i < resultList.size(); i++) {
			Object[] r = resultList.get(i);
			result[i] = new SelectItem((String) r[0], (String) r[1]);
		}
		return result;
	}

	private static void addManagedDepAndPerson(DepartmentalUnit du,
			List<String[]> resultList, Set<Integer> existedDU,
			String depLevelStr, String personLevelStr, int level) {
		if (existedDU.contains(du.getDepartmentalUnitId()))
			return;
		IOrganizationService orgService = SpringBeanHolder
				.getBean("orgService");
		existedDU.add(du.getDepartmentalUnitId());
		// 处理层次标识符
		String dLevelStr = "";
		if (level == 0)
			dLevelStr = "|—";
		else
			dLevelStr = depLevelStr + "——";
		String pLevelStr = personLevelStr + "——";
		List<SecurityUser> persons = orgService.getPersonsOfDept(du
				.getDepartmentalUnitId());
		// 把部门加上
		resultList.add(new String[] {
				PRI_DEPT + String.valueOf(du.getDepartmentalUnitId()),
				depLevelStr + du.getName() });
		// 处理部门下的人
		for (SecurityUser user : persons) {
			resultList.add(new String[] {
					PRI_PERSON + String.valueOf(user.getUserId()),
					personLevelStr + user.getFullname() });
		}
		// 出子部门
		List<DepartmentalUnit> subList = orgService.getDirectChildDepts(du
				.getDepartmentalUnitId());
		if (subList != null)
			for (DepartmentalUnit subDu : subList) {
				addManagedDepAndPerson(subDu, resultList, existedDU, dLevelStr,
						pLevelStr, level + 1);
			}
		// 出部门下的人的主管部门
		for (SecurityUser user : persons) {
			List<DepartmentalUnit> directDU = orgService
					.getDirectManagedDeps(user.getUserId());
			for (DepartmentalUnit subdu : directDU) {
				addManagedDepAndPerson(subdu, resultList, existedDU, dLevelStr,
						pLevelStr, level + 1);
			}
		}
	}
}
